/**
 * Copyright (C) 2010 DustedPixels.com
 */
package com.dustedpixels.io;

import java.io.IOException;

/**
 * Appendables
 *
 * @author Michal Pociecha-Los (micapolos@gmail.com)
 */
public final class Appendables {
  private Appendables() {}
  
  public static final class Indenting implements Appendable {

    private final Appendable appendable;
    private final StringBuffer indentBuffer;
    private boolean newline;

    public Indenting(Appendable appendable) {
      this.appendable = appendable;
      this.indentBuffer = new StringBuffer();
      this.newline = true;
    }
    
    public Indenting indent() {
      indentBuffer.append("  ");
      return this;
    }
    
    public Indenting unindent() {
      indentBuffer.setLength(indentBuffer.length() - 2);
      return this;
    }
    
    public Appendable append(char c) throws IOException {
      if (c == '\n') {
        newline = true;
      } else if (newline) {
        appendable.append(indentBuffer.toString());
        newline = false;
      }
      
      appendable.append(c);
      
      return this;
    }

    public Appendable append(CharSequence csq) throws IOException {
      return append(csq, 0, csq.length());
    }

    public Appendable append(CharSequence csq, int start, int end)
        throws IOException {
      for (int i = start; i < end; i++) {
        append(csq.charAt(i));
      }
      return this;
    }    
  }
}
